<?php

/**
 * Created by PhpStorm.
 * User: deng
 * Date: 2015/2/16
 * Time: 1:18
 */
namespace Common\Controller;

use Think\Controller\RestController;

require_once('Application/Common/Model/DB.php'); //引入DB.php
use \MongoClient;

vendor('Jwt.JWT');

class RestFulApiController extends ApiController
{
    protected $_request;
    protected $_db;
    protected $_model = null;
    protected $_baseModel;

    protected $_root = null;
    protected $_fields = [];
    protected $_cond = [];
    protected $_data = [];
    protected $_limit = 0;
    protected $_skip = 0;
    protected $_order = 'stat.createTime dsc';
    protected $_token = [];
    protected $_action = 'list';

    public function __construct()
    {
        parent::__construct();
        global $db;
        if (!isset($db)) {
            $db = \DB::build('Application/Common/Model/models/', (new MongoClient())->metalab);
        }
        $this->_db = $db;
    }

    protected function init()
    {
        $this->root();
        $this->fields();
        $this->data();
        $this->limit();
        $this->skip();
        $this->cond();
        $this->order();
        $this->token();
        $this->action();
    }

    public function index()
    {
        $conf = [
            'fields' => $this->_fields,
            'cond' => $this->_cond,
            'orderBy' => $this->_order,
            'skip' => $this->_skip,
            'limit' => $this->_limit
        ];
        if ($this->_action == 'count')
            $result['total'] = $this->_model->findBy($conf)['total'];
        else if ($this->_action == 'list')
            $result = $this->_model->findBy($conf)['list'];
        Success(C('CODE.OK')['code'], $result);
    }

    public function view($id)
    {
        Success(C('CODE.OK')['code'], $this->_model->find($id, $this->_fields));
    }

    public function create()
    {
        $this->checkAuth();
        $result = $this->_model->create($this->_data);
        Success(C('CODE.OK')['code'], $this->_model->find($result));
    }

    public function update($id)
    {
        $this->checkAuth();
        $this->_model->update($id, $this->_data);
        Success(C('CODE.OK')['code'], $this->_baseModel->find($id));
    }

    public function delete($id)
    {
        $this->checkAuth();
        Success(C('CODE.NO_CONTENT')['code'], $this->_model->remove($id));
    }

    public function checkAuth()
    {
        /**
         * 验证token
         */
        $array = $this->_token;
        if ($this->isExpired($array['expire']))
            ClientError('令牌已过期', C('CODE.FORBIDDEN')['code']);
        if ($userId = $array['userId']) {
            $usermodel = $this->_db->users;
            if ($usermodel->find($userId)) {
                ;
            } else
                ClientError('参数错误', C('CODE.UNAUTHORIZED')['code']);
        } else
            ClientError('未登录', C('CODE.UNAUTHORIZED')['code']);
    }

    public function isExpired($date)
    {
        if ($date < time())
            return true;
        return false;
    }

    private function root()
    {
        //对前台的参数root处理
        $this->_root = empty($this->_request['root']) ? $this->_root : $this->_request['root'];

        $this->_baseModel = $this->_model;
        if (!empty($this->_root)) {
            $root = explode('.', $this->_root);
            foreach ($root as $value => $r) {
                $r = $r . '';
                $this->_model = $this->_model->$r;
            }
        }
    }

    private function fields()
    {
        //对前台的参数feild处理
        $this->_fields = isset($this->_request['fields']) ? $this->_request['fields'] : $this->_fields;
        foreach ($this->_fields as $key => $value) {
            if (empty($value)) {
                unset($this->_fields[$key]);
            }
        }

    }

    private function data()
    {
        $this->_data = isset($this->_request['data']) ? $this->_request['data'] : $this->_data;
    }

    private function limit()
    {
        $this->_limit = isset($this->_request['limit']) ? $this->_request['limit'] : $this->_limit;
    }

    private function skip()
    {
        $this->_skip = isset($this->_request['skip']) ? $this->_request['skip'] : $this->_skip;
    }

    private function cond()
    {
        $this->_cond = isset($this->_request['cond']) ? $this->_request['cond'] : $this->_cond;
    }

    private function order()
    {
        $this->_order = isset($this->_request['order']) ? $this->_request['order'] : $this->_order;
    }

    private function action()
    {
        $this->_action = isset($this->_request['action']) ? $this->_request['action'] : $this->_action;
    }

    private function token()
    {
        $headers = getallheaders();
        $this->_token = isset($headers['X-Token']) ? $headers['X-Token'] : $this->_token;
        if ($this->_token)
            $this->_token = get_object_vars(\JWT::decode($this->_token, C('JWT.key')));
//        else
//            ClientError('参数错误', C('CODE.BAD_REQUEST')['code']);
    }
}